# -*- coding: utf-8 -*-
##############################################################################
#
#    Copyright (C) 2013 Agile Business Group sagl (<http://www.agilebg.com>)
#    Copyright (c) 2015 ACSONE SA/NV (<http://acsone.eu>)
#
#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU Affero General Public License as published
#    by the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU Affero General Public License for more details.
#
#    You should have received a copy of the GNU Affero General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################

from odoo import fields, models, api, _
from odoo.exceptions import UserError, AccessError
from odoo.exceptions import ValidationError
from odoo.tools import float_is_zero, float_compare, DEFAULT_SERVER_DATETIME_FORMAT


class PurchaseOrder(models.Model):
    _inherit = 'purchase.order'

    @api.multi
    def action_invoice_create(self, grouped=False, final=False):
        invo_obj = self.env['account.invoice']
        invo_id = invo_obj.create({
            'partner_id': self.partner_id.id,
            'journal_id': self.env['account.journal'].search([('type', '=', 'purchase')], limit=1).id,
            'purchase_id': self.id,
            'final': final,
            'account_id': self.partner_id.property_account_payable_id.id,
            'origin': self.name,
            'type': 'in_invoice',
        })
        invo_id.purchase_order_change_for_order()
        invo_id._onchange_invoice_line_ids()
        view = self.env.ref('account.invoice_supplier_form')
        if not final:
            return {
                'name': _(u'创建发票'),
                'type': 'ir.actions.act_window',
                'res_model': 'account.invoice',
                'view_id': [view.id],
                'view_type': 'form',
                'view_mode': 'form',
                'views': [(view.id, 'form')],
                'res_id': invo_id.id,
                'target': 'current',
                'context': {
                }
            }
        else:
            return {
                'name': _(u'创建发票'),
                'type': 'ir.actions.act_window',
                'res_model': 'account.invoice',
                'view_id': [view.id],
                'view_type': 'form',
                'view_mode': 'form',
                'views': [(view.id, 'form')],
                'res_id': invo_id.id,
                'target': 'current',
                'context': {
                }
            }
